﻿using MCronJob.Jobs;
using Quartz;
using Quartz.Spi;

namespace MCronJob
{
    public class SchedulerCenter
    {
        private readonly IJobFactory _jobFactory;
        private readonly ISchedulerFactory _schedulerFactory;
        private IScheduler _scheduler;
        public SchedulerCenter(IJobFactory jobFactory, ISchedulerFactory schedulerFactory)
        {
            _jobFactory = jobFactory;
            _schedulerFactory = schedulerFactory;
        }
        public async void StartScheduler()
        {
            //1、从工厂获取调度程序实例
            _scheduler = await _schedulerFactory.GetScheduler();

            // 替换默认工厂
            _scheduler.JobFactory = this._jobFactory;

            //2、打开调度器
            await _scheduler.Start();

            //3、定义作业详细信息并将其与HelloJob任务相关联
            IJobDetail job = JobBuilder.Create<HelloJob>()
                .WithIdentity("HelloJob", "HelloJobGroup")
                .Build();

            //4、配置触发条件：立即触发作业运行，然后每10秒重复一次
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("HelloJob", "HelloJobGroup")
                .StartNow()
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(10)
                    .RepeatForever())
                .Build();

            //5、将作业与触发条件添加到调度实例并进行关联
            await _scheduler.ScheduleJob(job, trigger);
        }
        public void StopScheduler()
        {
            _scheduler?.Shutdown(true).Wait(30000);
            _scheduler = null;
        }
    }
}